import time
from tqsdk import TqApi, TqAuth, TqKq
from rich.console import Console
from rich.table import Table
from rich import print as rprint

# 初始化控制台
console = Console()

def main():
    try:
        # 使用常用账号密码连接账户
        api = TqApi(account=TqKq(), auth=TqAuth("cps168", "alibaba"))
        account = api.get_account()

        console.print("正在查询账户持仓信息...", style="info")
        api.wait_update()
        # 获取所有持仓
        positions = api.get_all_positions()
        table = Table(title="账户持仓信息", show_lines=True)
        table.add_column("品种代码", justify="center")
        table.add_column("持仓数量", justify="center")
        table.add_column("多仓数量", justify="center")
        table.add_column("空仓数量", justify="center")
        table.add_column("昨仓数量", justify="center")
        table.add_column("今仓数量", justify="center")

        if positions:
            for symbol, position in positions.items():
                pos_long = position.pos_long
                pos_short = position.pos_short
                pos_long_his = position.pos_long_his
                pos_short_his = position.pos_short_his
                pos_long_today = position.pos_long_today
                pos_short_today = position.pos_short_today
                total_pos = pos_long + pos_short
                total_his = pos_long_his + pos_short_his
                total_today = pos_long_today + pos_short_today

                table.add_row(
                    symbol,
                    str(total_pos),
                    str(pos_long),
                    str(pos_short),
                    str(total_his),
                    str(total_today)
                )
        else:
            table.add_row("当前账户没有持仓。", "", "", "", "", "")

        rprint(table)
        api.close()
    except Exception as e:
        console.print(f"查询持仓信息时出错: {e}", style="error")
        # 打印异常堆栈信息，方便调试
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()
